package com.zh.business.modules.sys.web;

import com.zh.business.base.util.JsonResult;
import com.zh.business.modules.sys.domain.SysUser;
import com.zh.business.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @create 2019-12-07 22:50
 * @description
 **/
@RestController
@RequestMapping("/sys/user/")
@Api(value = "SysUserController", description = "系统用户")
public class SysUserController {

    @Resource
    private SysUserService userService;

    @ApiOperation(value = "登入", notes = "", httpMethod = "POST", response = JsonResult.class)
    @PostMapping(value = "/login", produces = {"application/json;charset=UTF-8"})
    //@RequiresPermissions("assets:allot:view")
    public Object login(@RequestBody SysUser sysUser) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getUserName(), sysUser.getPassword());
        try {
            subject.login(token);
        } catch (IncorrectCredentialsException e) {
            return JsonResult.fail("密码错误");
        }   catch (AuthenticationException e) {
            return JsonResult.fail("账号或密码错误！");
        } catch (AuthorizationException e) {
            return JsonResult.fail("没有权限");
        }
        return JsonResult.ok("登入成功",subject.getSession().getId());
    }


    @ApiOperation(value = "分页列表", notes = "", httpMethod = "GET", response = JsonResult.class)
    @GetMapping(value = "/getPageData", produces = {"application/json;charset=UTF-8"})
    @RequiresPermissions("sys:user:view")
    public Object getPageData(@RequestParam(required = true) Integer pageNum, @RequestParam(required = true) Integer pageSize, SysUser sysUser) {
        List<SysUser> list = userService.getList();
        return JsonResult.ok().data(list);
    }
}
